import axios from "axios";
import { spawn, ChildProcessWithoutNullStreams } from 'child_process'
import { debugConfig } from '../config'
import os from 'os'
import nodePath from 'path'


const getPath = (path: string) => {
    if (os.platform() === 'darwin') {
        return `${path}/Contents/MacOS/${nodePath.basename(path, '.app')}`
    }
    return path
}



export async function getUrls() {
    const res = []

    try {
        for (const key of Object.keys(debugConfig)) {
            let configs = await axios.get(`http://127.0.0.1:${debugConfig[key as keyof typeof debugConfig]}/json`)

            for (const config of configs.data) {
                const devUrl = key === 'node' ?
                    config.devtoolsFrontendUrl :
                    config.devtoolsFrontendUrl.replace(/\/devtools\//, 'devtools://devtools/bundled/')

                res.push({
                    ...config,
                    devUrl,
                })
            }
        }
    } catch {}

    return res
}


export function exec(path: string): Promise<{ debugList: DebugItem[]; handle:  ChildProcessWithoutNullStreams }> {
    return new Promise((resolve => {
        const handle = spawn(getPath(path),
            [ `--inspect=${debugConfig.node}`,
                `-remote-debugging-port=${debugConfig.pages}`
            ])

        setTimeout(() => {
            resolve({ debugList: getUrls() as unknown as  DebugItem[], handle })
        }, 3000)
    }))

}